
#ifndef XDISK_H
#define XDISK_H

#include "xtypes.h"

struct _xdisk_t;
typedef struct _xdisk_driver_t
{
    xfat_err_t (*open)(struct _xdisk_t *disk, void *init_data);
    xfat_err_t (*read)(struct _xdisk_t *disk, u8_t *buffer, u32_t start_sector, u32_t count);
    xfat_err_t (*write)(struct _xdisk_t *disk, u8_t *buffer, u32_t start_sector, u32_t count);
    xfat_err_t (*close)(struct _xdisk_t *disk);
} xdisk_driver_t;

typedef struct _xdisk_t
{
    char name[32 + 1];
    u32_t sector_size;
    u32_t total_sector;
    xdisk_driver_t *driver;
    void *data;
    void *path;
} xdisk_t;

#pragma pack(1)
typedef struct _mbr_part_t
{
    u8_t boot_active;          // 分区是否活动
    u8_t start_header;         // 起始header
    u16_t start_sector : 6;    // 起始扇区
    u16_t start_cylinder : 10; // 起始磁道
    u8_t system_id;            // 文件系统类型
    u8_t end_header;           // 结束header
    u16_t end_sector : 6;      // 结束扇区
    u16_t end_cylinder : 10;   // 结束磁道
    u32_t relative_sectors;    // 相对于该驱动器开始的相对扇区数
    u32_t total_sectors;       // 总的扇区数
} mbr_part_t;

typedef struct _mbr_t
{
    u8_t boot_code[446];
    mbr_part_t part_info[4];
    u8_t boot_msg[2];
} mbr_t;
#pragma pack()

/**
 * 文件系统类型
 */
typedef enum
{
    FS_NOT_VALID = 0x00,    // 无效类型
    FS_FAT32 = 0x01,        // FAT32
    FS_EXTEND = 0x05,       // 扩展分区
    FS_WIN95_FAT32_0 = 0xB, // FAT32
    FS_WIN95_FAT32_1 = 0xC, // FAT32
} xfs_type_t;

typedef struct _xdisk_part_t
{
    mbr_part_t *part_info;

    u32_t start_sector; // 相对于整个物理存储区开始的块序号
    u32_t total_sector; // 总的块数量
    xfs_type_t type;    // 文件系统类型
    xdisk_t *disk;

    struct _xdisk_part_t *prev;
    struct _xdisk_part_t *next;
} xdisk_part_t;


xfat_err_t xdisk_init(xdisk_t *disk, const char *name, xdisk_driver_t *driver, void *init_data);
xfat_err_t xdisk_read(xdisk_t *disk, u8_t *buffer, u32_t start_sector, u32_t count);
xfat_err_t xdisk_write(xdisk_t *disk, u8_t *buffer, u32_t start_sector, u32_t count);

xfat_err_t xdisk_parse(xdisk_t *disk, xdisk_part_t *part_root);

#endif
